<?php
namespace Plu\qdh\Plugins;

use Phalcon\Mvc\User\Plugin;

class HttpResponsePlugin extends Plugin {
	public function beforeExecuteRoute($event, $dispatcher) {
		$annotations = $this->annotations->getMethod(
			$dispatcher->getControllerClass(),
			$dispatcher->getActiveMethod()
		);

		if ($annotations->has('checkLogin')) {
			$annotation = $annotations->get('checkLogin');
			$this->checkLogin($annotation);
		}

		if ($annotations->has('cacheable')) {
			$annotation = $annotations->get('cacheable');
			$this->setResponseCache($annotation);
		}
	}

	public function afterExecuteRoute($event, $dispatcher) {
		$annotations = $this->annotations->getMethod(
			$dispatcher->getControllerClass(),
			$dispatcher->getActiveMethod()
		);

		if ($annotations->has('cache_control')) {
			$annotation = $annotations->get('cache_control');
			$this->setCacheControl($annotation);
		}
	}

	/**
	 * 检查用户是否登录
	 */
	private function checkLogin($annotation) {
		if (!$this->passport) {
			return false;
		}
		
		$isLogined = $this->passport->isLogined();
		if ($isLogined <= 0) {
			$callback = $annotation->getNamedArgument('callback');
			if ($callback) {

			} else {
				return $this->throwStatus406();
			}
		}
	}

	private function throwStatus406() {
		$this->response->setStatusCode(406, "Not Acceptable");
		$this->response->send();
		exit;
	}

	/**
	 * 设定缓存头信息
	 * @param public=true
	 * @param private=true
	 * @param no_cache=true
	 * @param no_transform=true
	 * @param must_revalidate=true
	 * @param proxy_revalidate=true
	 * @param max_age=seconds
	 * @param a_maxage=seconds
	 */
	private function setCacheControl($annotation) {
		$options = $annotation->getArguments();
		if ($options) {
			$options = array_shift($options);
			$this->response->setHeader('Cache-Control', $options);
		}
	}

	/**
	 * 缓存数据内容
	 *
	 * @param key 需要保存的key值
	 * @param lifetime 需要缓存的时间
	 */
	private function setResponseCache($annotation) {

	}
}
?>
